<script lang="tsx">
import { defineComponent, ref, watch, onUnmounted, computed } from 'vue';
import { Film, Play, CircleCheck } from '@vben/icons';
import { obsDownload } from '#/utils/obs';

export default defineComponent({
  name: 'PlayVideo',
  components: {
    Film,
    Play,
    CircleCheck
  },
  props: {
    url: {
      type: String,
      default: ''
    },
    visible: {
      type: Boolean,
      default: false
    }
  },
  emits: ['close'],
  setup(props, { emit }) {
    const currentVideo = ref<any>(null);
    const videoLoading = ref<boolean>(false);
    
    // 使用计算属性处理 v-model，避免直接修改 prop
    const dialogVisible = computed({
      get: () => props.visible,
      set: (value: boolean) => {
        if (!value) {
          emit('close');
        }
      }
    });
    
    // 监听 modelValue 变化，用于回显
    watch(() => props.url, (newValue) => {
      if (newValue) {
        // 通过obs下载文件流获取视频URL
        try {
          videoLoading.value = true;
          obsDownload({
            Key: newValue
          }, (err: any, result: any) => {
            if (err) {
              console.error('获取视频文件失败:', err);
              return;
            }

            // 创建视频Blob URL
            const content = result.InterfaceResult.Content as ArrayBuffer;
            const blob = new Blob([content], {
              type: 'video/mp4'
            });
            const videoUrl = window.URL.createObjectURL(blob);

            currentVideo.value = {
              name: props.url,
              url: videoUrl,
            };
            videoLoading.value = false;
          });
        } catch (error) {
          videoLoading.value = false;
        }

      } else {
        // 清空
        currentVideo.value = null;
      }
    }, { immediate: true });

    // 组件销毁时清理URL
    onUnmounted(() => {
      if (currentVideo.value && currentVideo.value.url) {
        URL.revokeObjectURL(currentVideo.value.url);
      }
    });

    const handleClose = () => {
      emit('close');
    };

    return {
      currentVideo,
      dialogVisible,
      videoLoading,
      handleClose
    };
  }
});
</script>
<template>
  <el-dialog v-model="dialogVisible" :title="$t('competition.newsMgr.playVideo')" width="50%" :close-on-click-modal="false" @close="handleClose">
    <div v-loading="videoLoading" class="video-upload-container min-h-[50px]">
      <div v-if="currentVideo" class="video-preview pb-[20px]">
        <video :src="currentVideo.url" class="video-player" controls preload="metadata">
        </video>
      </div>
    </div>
  </el-dialog>
</template>
<style lang="scss" scoped>
.video-upload-container {
  .video-preview {
    width: 100%;
    height: 100%;
    :deep(.video-player) {
      width: 100%;
      height: 100%;
    }
  }
}
</style>
